<template>
	<w-app-container class="app-home">
		<fx-page-header title="车间"></fx-page-header>
		<fxListFilter @resetSearch='resetSearch'>
					<template slot="row-1" >
						<el-form-item label="车间：">
								<!-- <w-select ref='workShopSelect' multiple clearable collapseTags :optionlist='workShopList'>
								</w-select> -->
								<w-select-mulity
									ref='workShopSelect'
									:optionlist="workShopList"
									class="form-input"
								>
								</w-select-mulity>
						</el-form-item>
						<el-form-item label="车间类型：" label-width="110px">
								<!-- <w-select ref='workShopTypeSelect' multiple clearable collapseTags :optionlist='workShopTypeList'>
								</w-select> -->
								<w-select-mulity
									ref='workShopTypeSelect'
									:optionlist="workShopTypeList"
									class="form-input"
								>
								</w-select-mulity>
						</el-form-item>
						<el-form-item label="启停状态：" label-width="110px">
								<el-select v-model="enableState" prop="enableState" placeholder="请选择" clearable size='mini' class="form-input">
									<el-option
										v-for="item in stateList"
										:key="item.id"
										:label="item.label"
										:value="item.id"
									>
									</el-option>
								</el-select>
						</el-form-item>
					</template>
					<template slot="tools">
						<el-row>
							<el-button type="primary" size='mini' @click="searchWorkShop">查询</el-button>
							<el-button type="text" size='mini' @click="resetSearch">重置</el-button>
						</el-row>
					</template>
		</fxListFilter>
		<w-app-container direction="row" class="fx-page-first-container">
			<div class="tree-container">
				<fxTree :treeData="treeData" @node-click="nodeClick"></fxTree>
			</div>
			<w-table
					ref="multipleTable"
					:listData="workShopData"
					:tableColumn="workShopColumns"
					:showPagination="true"
					:showColumnFilterBtn="false"
					minWidth="100px"
					:listTotal="totalCount"
					@on-table-row-dbclick="editRow"
					@on-size-change="handleSizeChange"
					@on-current-change="handleCurrentChange">
					<div slot="btn-tools-right" class="tools-right">
							<el-button type="danger" plain size='mini' @click="mutileDel">删除</el-button>
							<el-button type="success" plain size='mini' @click="mutileEnable">启用</el-button>
							<el-button type="info" plain size='mini' @click="mutileDiable">停用</el-button>
							<el-button type="primary"	size='mini' icon="el-icon-plus">导入车间</el-button>
							<el-button type="primary"	size='mini' icon="el-icon-plus" @click="addWorkShop">新建车间</el-button>
					</div>
			</w-table>
		</w-app-container>
		<el-dialog :title="dialogTitle" :visible.sync="workShopInfoDialogVisible" width='480px'  :before-close="beforeClose">
				<div class="create-area">
				<el-form :model="WorkShopForm" label-position='right' label-width='100px'  :rules="WorkShopRules" ref="WorkShopForm" size='mini'>
						<el-form-item label="车间编号" prop="code" label-width="110px">
								<el-input v-model="WorkShopForm.code" autocomplete="off" class="form-item-input"></el-input>
						</el-form-item>
						<el-form-item label="车间名称" prop="name" label-width="110px">
								<el-input v-model="WorkShopForm.name" autocomplete="off" class="form-item-input"></el-input>
						</el-form-item>
						<el-form-item label="车间类型" prop="carTypeNameId" label-width="110px">
								<w-select :multiple='false' v-model="WorkShopForm.carTypeNameId" allowCreate
								:clearable='true' :collapseTags='false' :optionlist='workShopTypeList' :isBlock='true' @blur="carTypeBlur" class="form-item-input">
								</w-select>
						</el-form-item>
						<el-form-item label="所属工厂" prop="factoryId" label-width="110px">
								<w-select :multiple='false' v-model="WorkShopForm.factoryId"
								:clearable='true' :optionlist='workShopFactoryList' :isBlock='true' class="form-item-input">
								</w-select>
						</el-form-item>
						<el-form-item label="联系人" prop="contactName" label-width="110px">
								<el-input v-model="WorkShopForm.contactName" autocomplete="off" class="form-item-input"></el-input>
						</el-form-item>
						<el-form-item label="电话" prop="mobile" label-width="110px">
								<el-input v-model="WorkShopForm.mobile" autocomplete="off" class="form-item-input"></el-input>
						</el-form-item>
						<el-form-item label="启停状态" prop="enable" label-width="110px">
								<el-switch v-model="WorkShopForm.enable" active-color="#13ce66" inactive-color="#ff4949" active-value="1" inactive-value="0"></el-switch>
						</el-form-item>
						<el-form-item label="备注" prop="remark" label-width="110px">
								<el-input
									v-model="WorkShopForm.remark"
									type="textarea"
									:rows="3"
									:maxlength="200"
									placeholder="请输入备注"
									class="form-item-input"
									show-word-limit
									resize="none"
								/>
						</el-form-item>
				</el-form>
				</div>
				<div slot="footer" class="dialog-footer">
						<el-button @click="doClose">取 消</el-button>
						<el-button type="primary" @click="doSave('WorkShopForm')">保 存</el-button>
				</div>
		</el-dialog>
	</w-app-container>
</template>
<script>
import fxListFilter from '@/components/common/Fx-list-filter.vue'
import fxTree from '@/components/common/Fx-tree.vue'
import APP_STATE_CONFIG from '@/config/app_state_config.js'
import FxListStateTag from '@/components/common/Fx-list-state-tag.vue'
export default {
	name: 'workshop',
	components: {
		fxListFilter,
		fxTree
	},
	data () {
		return {
			tableHeight: (document.body.clientHeight - 200) + 'px',
			treeData: [],
			selTreeNode: '',
			stateList: APP_STATE_CONFIG.enableState,
			workShopList: [],
			workShopTypeList: [],
			workShopFactoryList: [],
			enableState: '',
			workShopData: [],
			workShopColumns: [
				{ prop: 'code', label: '车间编码', required: true, width: '80px' },
				{ prop: 'name', label: '车间名称', required: true, showOverflowTooltip: true },
				{ prop: 'factoryName', label: '所属工厂', required: true, showOverflowTooltip: true },
				{ prop: 'carTypeName', label: '车间类型', required: true, showOverflowTooltip: true },
				{
					prop: 'enable',
					label: '启停状态',
					required: true,
					fxRender: this.enableRender
				},
				{ prop: 'remark', label: '备注', required: true, showOverflowTooltip: true },
				{
					prop: 'modifyUser', label: '修改人', required: true
				},
				{
					prop: 'modifyDate', label: '修改时间', required: true
				},
				{
					prop: 'createUser', label: '创建人', required: true
				},
				{
					prop: 'createDate', label: '创建时间', required: true
				}
			],
			totalCount: 0,
			workShopInfoDialogVisible: false,
			dialogTitle: '',
			WorkShopForm: {
				code: '',
				name: '',
				carTypeId: '',
				factory: '',
				enable: '1',
				remark: ''
			},
			addWorkShopTypeName: '',
			WorkShopRules: {
				code: [
					{ required: true, message: '请输入车间编号', trigger: 'change' },
					{ min: 1, max: 18, message: '长度最多18个字符', trigger: 'blur' }
				],
				name: [
					{ required: true, message: '请输入车间名称', trigger: 'change' },
					{ min: 1, max: 50, message: '长度最多50个字符', trigger: 'blur' }
				],
				carTypeNameId: [
					{ min: 1, max: 50, message: '长度最多50个字符', trigger: 'blur' }
				],
				contactName: [
					{ min: 1, max: 50, message: '长度最多50个字符', trigger: 'blur' }
				],
				mobile: [
					{ min: 1, max: 20, message: '长度最多20个字符', trigger: 'blur' }
				],
				factoryId: [
					{ required: true, message: '请选择所属工厂', trigger: 'change' }
				],
				remark: [
					{ min: 1, max: 200, message: '长度最多200个字符', trigger: 'blur' }
				]
			},
			fxDataVerification: null
		}
	},
	created () {
		// 获取左侧树数据
		this.getTreeData()
		// 获取车间下拉选择项
		this.getWorkShop()
		this.getWorkShopType()
		this.onRefreshWorkShopList()
	},
	computed: {
		enableFormaterState (val, key) {
			return (val, key) => {
				return this.$fxStateMiddleware.getStateObj('enableState')(val)[key]
			}
		}
	},
	methods: {
		// 树节点点击
		nodeClick (data, node) {
			this.selTreeNode = data.id
			this.onRefreshWorkShopList()
		},
		getTreeData () {
			this.getTreeDataPost().then(res => {
				this.treeData = res
			})
		},
		getTreeDataPost () {
			return new Promise(resolve => {
				this.$fxApi('workshop.orginTree')({
					query: {
						level: '2'
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		getWorkShop () {
			this.getAllWorkShopList().then(res => {
				this.workShopList = res
			})
		},
		getWorkShopType () {
			return new Promise(resolve => {
				this.getAllWorkShopType().then(res => {
					this.workShopTypeList = res
					resolve(res)
				})
			})
		},
		// 获取车间下拉选择数据
		getAllWorkShopList () {
			return new Promise(resolve => {
				this.$fxApi('workshop.findListAll').then(res => {
					resolve(res)
				})
			})
		},
		// 获取车间类型
		getAllWorkShopType () {
			return new Promise(resolve => {
				this.$fxApi('workshop.findCarRoomTypeListAll').then(res => {
					resolve(res)
				})
			})
		},
		// 获取车间所属工厂
		getFactoryList () {
			return new Promise(resolve => {
				this.$fxApi('workshop.findFactoryList').then(res => {
					resolve(res)
				})
			})
		},
		// 列表数据
		onRefreshWorkShopList () {
			const searchParams = {
				pageNum: (this.$refs.multipleTable && this.$refs.multipleTable.getPaginationParams().pageNum) || 1,
				pageSize: (this.$refs.multipleTable && this.$refs.multipleTable.getPaginationParams().pageSize) || 20
			}
			var params = {}
			if (this.enableState !== '') {
				params.enable = this.enableState
			}
			// 车间下拉
			if (this.$refs.workShopSelect && this.$refs.workShopSelect.currentValue.length >= 1) {
				params.carRoomIds = this.$refs.workShopSelect.currentValue
			}
			// 车间类型下拉
			if (this.$refs.workShopTypeSelect && this.$refs.workShopTypeSelect.currentValue.length >= 1) {
				params.carTypeNameIds = this.$refs.workShopTypeSelect.currentValue
			}
			if (this.selTreeNode) {
				params.treeId = this.selTreeNode
			}
			if (Object.keys(params).length !== 0) {
				searchParams.params = params
			}
			return new Promise(resolve => {
				this.$fxApi('workshop.findAllWorkShops')({
					data: searchParams
				}).then(res => {
					this.totalCount = this.$fxUtils.toNumber(res.total)
					this.workShopData = res.data
					// this.$refs.multipleTable.clearSelected()
					resolve()
				})
			})
		},
		handleSizeChange (val) {
			this.onRefreshWorkShopList()
		},
		handleCurrentChange (val) {
			this.onRefreshWorkShopList()
		},
		addWorkShop () {
			return new Promise(resolve => {
				Promise.all([
					this.getAllWorkShopType(),
					this.getFactoryList(),
					this.getNextCode()
				]).then(([shoplist, factorylist, newCode]) => {
					this.workShopTypeList = shoplist
					this.workShopFactoryList = factorylist
					this.showDialog(newCode)
					resolve()
				})
			})
		},
		showDialog (code) {
			this.workShopInfoDialogVisible = true
			if (this.$refs.WorkShopForm) {
				this.$refs.WorkShopForm.resetFields()
			}
			this.WorkShopForm.code = code
			this.WorkShopForm.id = ''
			this.addWorkShopTypeName = ''
			this.fxDataVerification = this.$fxUtils.fxDataVerification(this.WorkShopForm)
			this.dialogTitle = '新建车间'
		},
		renderWorkShopInfo (res) {
			const { code, id, contactName, enable, mobile, name, remark, factoryId, carTypeNameId } = res
			this.WorkShopForm = {
				code,
				id,
				contactName,
				enable,
				mobile,
				name,
				remark,
				factoryId,
				carTypeNameId
			}
			this.WorkShopForm.enable = res.enable ? '1' : '0'
			this.fxDataVerification = this.$fxUtils.fxDataVerification(this.WorkShopForm)
		},
		doClose () {
			this.VerityCompanyData()
		},
		beforeClose () {
			this.VerityCompanyData()
		},
		VerityCompanyData () {
			const isChange = !this.fxDataVerification.checkData(this.WorkShopForm)
			if (isChange) {
				this.$fxCommon.orderListFrontFunc('VeritybeforeClose').then(() => {
					this.doSave('WorkShopForm')
				}).catch(() => {
					this.workShopInfoDialogVisible = false
				})
				return false
			} else {
				this.workShopInfoDialogVisible = false
			}
		},
		// 车间类型 失去焦点
		carTypeBlur (e, value) {
			if (value) {
				this.addWorkShopTypeName = value
			}
		},
		doSave (formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.saveOrUpdateWorkShop().then(this.$fxCommon.orderSuccess('save')).then(() => {
						this.workShopInfoDialogVisible = false
						this.onRefreshWorkShopList()
					})
				} else {
					return false
				}
			})
		},
		editRow (row, column, event) {
			this.workShopInfoDialogVisible = true
			this.dialogTitle = '修改车间'
			return new Promise(resolve => {
				Promise.all([
					this.getAllWorkShopType(),
					this.getFactoryList(),
					this.findGroupDetailById(row)
				]).then(([shoplist, factorylist, detail]) => {
					this.workShopTypeList = shoplist
					this.workShopFactoryList = factorylist
					this.renderWorkShopInfo(detail)
					resolve()
				})
			})
			// this.findGroupDetailById(row).then(this.renderWorkShopInfo)
		},
		// 批量删除
		mutileDel () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('deleteMulity', _selData)
				.then(this.deleteWorkShop)
				.then(this.$fxCommon.orderSuccess('deleteMulity'))
				.then(this.onRefreshWorkShopList)
		},
		// 批量启用
		mutileEnable () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('enableMulity', _selData).then(() => {
				this.handleState(1).then(this.$fxCommon.orderSuccess('enableMulity')).then(this.onRefreshWorkShopList)
			})
		},
		// 批量停用
		mutileDiable () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('disableMulity', _selData).then(() => {
				this.handleState(0).then(this.$fxCommon.orderSuccess('disableMulity')).then(this.onRefreshWorkShopList)
			})
		},
		// 启用 停用
		handleState (type) {
			const _selData = this.$refs.multipleTable.selectedRowArr
			const ids = _selData.map(workshop => workshop.id)
			return new Promise(resolve => {
				this.$fxApi('workshop.updateEnable')({
					data: {
						carRoomIds: ids,
						enable: type
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		resetSearch () {
			this.enableState = ''
			this.$refs.workShopSelect.currentValue = []
			this.$refs.workShopTypeSelect.currentValue = []
		},
		// 查询集团
		searchWorkShop () {
			this.onRefreshWorkShopList()
		},
		// 获取编号
		getNextCode () {
			return new Promise(resolve => {
				this.$fxApi('workshop.getNextCode').then(res => {
					resolve(res)
				})
			})
		},
		// 获取集团信息
		findGroupDetailById (row) {
			return new Promise(resolve => {
				this.$fxApi('workshop.findGroupDetailById')({
					query: {
						id: row.id
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		// 新建更新集团信息
		saveOrUpdateWorkShop () {
			const { code, id, contactName, enable, mobile, name, remark, factoryId } = this.WorkShopForm
			const postData = {
				id,
				code,
				contactName,
				enable,
				mobile,
				name,
				remark,
				factoryId
			}
			// 当是新建车间类型的时候
			if (this.addWorkShopTypeName) {
				postData.archiveTypeDTO = {
					id: '',
					name: this.addWorkShopTypeName
				}
			} else {
				if (this.WorkShopForm.carTypeNameId) {
					postData.archiveTypeDTO = {
						id: this.WorkShopForm.carTypeNameId,
						name: ''
					}
				}
			}
			return new Promise(resolve => {
				this.$fxApi('workshop.saveOrUpdate')({
					data: postData
				}).then(res => {
					resolve(res)
				})
			})
		},
		// 删除集团信息
		deleteWorkShop () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			const ids = []
			_selData.forEach((v) => {
				ids.push(v.id)
			})
			return new Promise(resolve => {
				this.$fxApi('workshop.deleteWorkShopMulity')({
					data: {
						carRoomIds: ids
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		enableRender (h, { row }) {
			return <FxListStateTag
				icon={this.enableFormaterState(row.enable, 'icon')}
				label={this.enableFormaterState(row.enable, 'label')}
			></FxListStateTag>
		}
	}
}
</script>
<style lang="stylus" scoped>
@import '~$assets/stylus/varsty.styl';
.create-area {
	width: 100%
	height: 400px
	box-sizing: border-box
	.form-item-input {
		width:280px
	}
}
.form-input {
	width: 170px
}
.tree-container {
	display: flex
}
</style>

